import sys
import pdb
import threading
import multiprocessing
import MSLib as lib
g_name = 'ms driver'
CONFIG_NAME = 'glonass3_config.cfg'
lib.MSLogger.init(CONFIG_NAME)
log = lib.MSLogger.get('ms.main')

log.info(g_name + ' starting as %s' % (str(sys.argv)))

def readAPIObjects(isTerminated, database):
    log.info('readAPIObjects: started')

    try:
        cfg = lib.MSConfig.getConfig(CONFIG_NAME)
        reader = lib.MSAPIReader(cfg.get('msapi', 'url'))
    except Exception, err:
        log.info('readAPIObjects: can\'t start: %s', str(err))
        return

    objects = {}
    ctr = 0

    try:
        while not isTerminated.isSet():
            if (ctr % 100 == 0):
                try:
                    ctr = 0
                    lib.MSObjects.readObjectsFromFile(cfg.get('msapi', 'objects_cfg'), objects)
                    log.info('readAPIObjects: loaded %d objects from %s', len(objects), cfg.get('msapi', 'objects_cfg'))
                except Exception, err:
                    log.error('readAPIObjects: can\'t load objects: %s', str(err))
                log.info('readAPIObjects: status format: all:pgsm:cid:written')
            allevents = []
            written = 0
            try:
                eventsGPS = reader.getEventsGPS_ForSochi(objects)
                allevents += eventsGPS
            except Exception, err:
                log.error('readAPIObjects: can\'t read events: %s', str(err))

            try:
                database.append(allevents)
            except Exception, err:
                log.error('readAPIObjects: can\'t append events: %s', str(err))

            log.info('readAPIObjects: %d:%d', len(allevents), written)
            ctr += 1
            lib.time.sleep(2)
    except Exception, err:
        log.error('readAPIObjects: fatal error: %s' % (str(err)))

log.info('starting threads... ')
isTerminated = threading.Event()
isTerminated.clear()
database = lib.MSRuntimeDatabase()

#normalObjectsFromMSAPI  = multiprocessing.Process(target=readAPIObjects, name='normalObjectsFromMSAPI', args=(isTerminated, database))
normalObjectsFromMSAPI  = threading.Thread(target=readAPIObjects, name='normalObjectsFromMSAPI', args=(isTerminated, database))
try:
    #start them
    normalObjectsFromMSAPI.start()
    #check them
    lib.time.sleep(5)
    if not normalObjectsFromMSAPI.is_alive(): raise RuntimeError('normalObjectsFromMSAPI is not alive')
except Exception, err:
    log.error('can\'t start threads: ' + str(err))
    sys.exit(2)

log.info(g_name + ' started. Waiting for stop signal...')
try:
    while True:
        lib.time.sleep(2)
        database.cleanup()
except KeyboardInterrupt:
    log.info(g_name + ' stopping: %s' % (str(sys.argv)))
    sys.exit(0)
except Exception, err:
    log.error(g_name + ' stopping, fatal error: %s' % (str(err)))
    sys.exit(5)
finally:
    try:
        isTerminated.set()
        normalObjectsFromMSAPI.join()
        log.info('stopped')
    except Exception, err:
        log.error('error while exiting: ' + str(err))
        sys.exit(4)
